// pages/product/product/product.js
import { getProductNav,getGoodsList } from '../../../network/product'
import { debounce } from '../../../utils/Tools'
Page({
  data: {
    search:null,
    brand: [],
    category: [],
    norms: [],
    method: [],
    screen:{
      brand:0,category:0,norms:0,method:0
    },
    goodslist:[],
    afterList:[],
    isScroll:false
  },
  onLoad: function (options) {
    this.handleFilter = debounce(this.handleFilter,300)
    this.getProductList = debounce(this.getProductList,1000)

    //  调用网络请求
    this.handleAllPro()
    this._getProductNav()
  },
  //      函数事件       //
  forbidScroll(e) {
    return;
  },
  openDownMenu(){
    this.setData({isScroll:true})
  },
  closeDownMenu(){
    this.setData({isScroll:false})
  },
  handleDownMenu(e){  //    处理导航下拉菜单
    const {type} = e.currentTarget.dataset
    this.setData({
      [`screen.${type}`]:e.detail
    })
    this.getProductList()
  },
  async handleFilter(e){
    const result = this.data.goodslist.filter(res =>{
    return res.product_name.includes(e.detail)
  })
    if(!result) this.setData({afterList: this.data.goodslist})
    this.setData({afterList:result})
  },
  assignNav(arr,cate){
    arr.forEach((res,index) => {
      this.setData({
        [cate]: this.data[cate].concat({text:res,value:index})
      })
    });
  },
  async handleAllPro(){
    const result = await getGoodsList()
    this.setData({
      goodslist:result.data,
      afterList: result.data
    })
  },
  //      网络请求方法     //
  async _getProductNav(){  // 获取产品导航
    const res = await getProductNav()
    if(res.code === 200){
      this.assignNav(res.data.brand,"brand")
      this.assignNav(res.data.category,"category")
      this.assignNav(res.data.standards,"norms")
      this.assignNav(res.data.pack_method,"method")
    }
  },
  async getProductList(){
    const data = { //  获取筛选产品所需参数
      brand: this.data.brand[this.data.screen.brand].text,
      category: this.data.category[this.data.screen.category].text,
      standards:this.data.norms[this.data.screen.norms].text,
      pack_method:this.data.method[this.data.screen.method].text
    }
    const result = await getGoodsList(data)
    if(result.code === 200){
      this.setData({
        goodslist:result.data,
        afterList: result.data
      })
    }
  }
})